package com.example.utils;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.example.shop.DBHelper;
import com.example.shop.User;


public class UserDataUtils {
    private static UserDataUtils instance = null;
    private static SQLiteDatabase db;

    public UserDataUtils(Context context) {
        DBHelper helper = new DBHelper(context);
        db = helper.getWritableDatabase();
    }

    public static UserDataUtils getInstance(Context context) {
        if (instance == null) {
            instance = new UserDataUtils(context);
        }
        return instance;
    }

    public void saveUserInfo(User user) {
        ContentValues cv = new ContentValues();
        cv.put("userName", user.userID);
        cv.put("nickName", user.nickName);
        cv.put("sex", user.sex);
        cv.put("signature", user.signature);
        db.insert(DBHelper.U_USERINFO, null, cv);
    }

    public User getUserInfo(String userName) {
        String sql = "SELECT * FROM " + DBHelper.U_USERINFO + " WHERE userName=?";
        Cursor cursor = db.rawQuery(sql, new String[]{userName});
        User user = null;
        while (cursor.moveToNext()) {
            user = new User();
            user.userID = cursor.getString(cursor.getColumnIndex("userName"));
            user.nickName = cursor.getString(cursor.getColumnIndex("nickName"));
            user.sex = cursor.getString(cursor.getColumnIndex("sex"));
            user.signature = cursor.getString(cursor
                    .getColumnIndex("signature"));
        }
        cursor.close();
        return user;
    }

    public void updateUserInfo(String key, String value, String userName) {
        ContentValues cv = new ContentValues();
        cv.put(key, value);
        db.update(DBHelper.U_USERINFO, cv, "userName=?",
                new String[]{userName});
    }

}